package cc.shacocloud.mirage.utils.converter.support;

import cc.shacocloud.mirage.utils.converter.ConversionSupport;
import cc.shacocloud.mirage.utils.converter.TypeDescriptor;
import org.jetbrains.annotations.NotNull;

import java.time.Duration;
import java.time.temporal.TemporalAmount;

/**
 * 转换为 {@link Duration} 类型的转换器
 *
 * @author 思追(shaco)
 */
public class ToDurationConversion extends AbstractConversion implements ConversionSupport {
    
    @Override
    public boolean support(@NotNull TypeDescriptor sourceType, @NotNull TypeDescriptor targetType) {
        Class<?> objectType = targetType.getObjectType();
        return Duration.class.equals(objectType);
    }
    
    @Override
    public Object convert(@NotNull Object source, @NotNull TypeDescriptor sourceType, @NotNull TypeDescriptor targetType) {
        if (source instanceof Duration) {
            return source;
        } else if (source instanceof TemporalAmount) {
            return Duration.from((TemporalAmount) source);
        } else if (source instanceof Long) {
            return Duration.ofMillis((Long) source);
        } else {
            return Duration.parse(convertToStr(source));
        }
    }
}
